import { RouteRecordRaw, createRouter, createWebHashHistory } from "vue-router";
import pageRouter from "./page/index";
import viewsRouter from "./views/index";
import { useStore } from "/@/store";
import { MutationTypes } from "../store/user/mutation-types";
import { defaultRoutePath, loginRoutePath } from "./config";
import NOT_FOUND from "/@/components/default/404.vue";
const routes: RouteRecordRaw[] = [
  ...pageRouter,
  ...viewsRouter,
  {
    path: "/:pathMatch(.*)*",
    name: "404",
    component: NOT_FOUND,
  },
];

// 生产环境加载bug 先用hash
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach(async (to, _from, next) => {
  const store = useStore();
  const meta = to.meta || {};
  // 轻刷新从 store 获取 userInfo
  if (!store.state.userInfo.isLogin) {
    // 如果用户重刷新则, 从 localStorage 里获取 userInfo
    store.commit(MutationTypes.GET_USER_INFO);
    // 系统初始化
    // store.dispatch(SysActionTypes.SYS_INIT);
    if (!store.state.userInfo.isLogin) {
      if (meta.isAuth === false) {
        next();
      } else {
        next({
          path: "/login",
        });
      }
      // if (store.state.ws) {
      //   store.state.ws.close();
      //   store.state.ws = undefined;
      // }
      return;
    }
  }
  if (to.path === loginRoutePath) {
    next(defaultRoutePath);
  } else {
    next();
  }
  // if (to.path === "/home") {
  //   // 连接消息
  //   store.dispatch(SysActionTypes.SYS_SET_WS);
  // }
});

export default router;
